/*******************************************************************************
 * Copyright 2009-2015 Amazon Services. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License"); 
 *
 * You may not use this file except in compliance with the License. 
 * You may obtain a copy of the License at: http://aws.amazon.com/apache2.0
 * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR 
 * CONDITIONS OF ANY KIND, either express or implied. See the License for the 
 * specific language governing permissions and limitations under the License.
 *******************************************************************************
 * Marketplace Web Service Orders
 * API Version: 2013-09-01
 * Library Version: 2015-04-30
 * Generated: Thu May 28 20:14:49 GMT 2015
 */
package com.amazonservices.mws.orders._2013_09_01.samples;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import com.alibaba.fastjson.JSON;
import com.amazon.orderslist.AmazonOrdersList;
import com.amazon.orderslist.Order;
import com.amazon.orderslist.OrderTotal;
import com.amazon.orderslist.ShippingAddress;
import com.amazonservices.mws.orders._2013_09_01.MarketplaceWebServiceOrders;
import com.amazonservices.mws.orders._2013_09_01.MarketplaceWebServiceOrdersClient;
import com.amazonservices.mws.orders._2013_09_01.MarketplaceWebServiceOrdersException;
import com.amazonservices.mws.orders._2013_09_01.model.ListOrdersByNextTokenRequest;
import com.amazonservices.mws.orders._2013_09_01.model.ListOrdersByNextTokenResponse;
import com.amazonservices.mws.orders._2013_09_01.model.ResponseHeaderMetadata;
import com.idp.ebay.domain.AmazonInfo;
import com.idp.ebay.utils.ExcelFileUtil;

import cn.creditharmony.loan.util.Xml2JsonUtil;

/** Sample call for ListOrdersByNextToken. */
public class ListOrdersByNextTokenSample {

	/**
	 * Call the service, log response and exceptions.
	 *
	 * @param client
	 * @param request
	 *
	 * @return The response.
	 */
	public static ListOrdersByNextTokenResponse invokeListOrdersByNextToken(MarketplaceWebServiceOrders client,
			ListOrdersByNextTokenRequest request) {
		try {
			// Call the service.
			ListOrdersByNextTokenResponse response = client.listOrdersByNextToken(request);
			ResponseHeaderMetadata rhmd = response.getResponseHeaderMetadata();
			// We recommend logging every the request id and timestamp of every
			// call.
			System.out.println("Response:");
			System.out.println("RequestId: " + rhmd.getRequestId());
			System.out.println("Timestamp: " + rhmd.getTimestamp());

			String responseXml = response.toXML();
			/* System.out.println(responseXml); */
			String jsonstr = Xml2JsonUtil.xml2JSON(responseXml);

			ExcelFileUtil excel = new ExcelFileUtil();
			List<AmazonInfo> ebst = new ArrayList<AmazonInfo>();

			System.out.println(jsonstr);

			AmazonOrdersList a2 = JSON.parseObject(jsonstr, AmazonOrdersList.class);

			String nextToken = a2.getListOrdersByNextTokenResponse().getListOrdersByNextTokenResult().get(0)
					.getNextToken().get(0).toString();

			System.out.println(nextToken);

			Order ord = a2.getListOrdersByNextTokenResponse().getListOrdersByNextTokenResult().get(0).getOrders().get(0)
					.getOrder().get(0);

			ShippingAddress s = ord.getShippingAddress().get(0);

			String shipAddress = s.toString();

			OrderTotal orderTotals = ord.getOrderTotal().get(0);

			String orderTotal = orderTotals.toString();

			String EarliestDeliveryDate = "";
			String EarliestShipDate = "";
			String ShippedByAmazonTFM = "";
			String ShipServiceLevel = "";
			String LatestDeliveryDate = "";
			String PurchaseDat = "";

			if (ord.getEarliestDeliveryDate() == null) {
				EarliestDeliveryDate = "";
			} else {
				EarliestDeliveryDate = ord.getEarliestDeliveryDate().toString();
			}

			if (ord.getEarliestShipDate() == null) {
				EarliestShipDate = "";
			} else {
				EarliestShipDate = ord.getEarliestShipDate().toString();
			}

			if (ord.getShippedByAmazonTFM() == null) {
				ShippedByAmazonTFM = "";
			} else {
				ShippedByAmazonTFM = ord.getShippedByAmazonTFM().get(0);
			}

			if (ord.getShipServiceLevel() == null) {
				ShipServiceLevel = "";
			} else {
				ShipServiceLevel = ord.getShipServiceLevel().get(0);
			}

			if (ord.getLatestDeliveryDate() == null) {
				LatestDeliveryDate = "";
			} else {
				LatestDeliveryDate = ord.getLatestDeliveryDate().toString();
			}

			if (ord.getPurchaseDate() == null) {
				PurchaseDat = "";
			} else {
				PurchaseDat = ord.getPurchaseDate().toString();
			}

			AmazonInfo amazonInfo = new AmazonInfo(ord.getAmazonOrderId().get(0), ord.getBuyerEmail().get(0),
					EarliestDeliveryDate, EarliestShipDate, ord.getSalesChannel().get(0), ord.getOrderStatus().get(0),
					ord.getNumberOfItemsShipped().get(0), ord.getOrderType().get(0), ord.getIsPremiumOrder().get(0),
					ord.getIsPrime().get(0), ord.getBuyerName().get(0), ord.getFulfillmentChannel().get(0),
					ord.getNumberOfItemsShipped().get(0), ord.getLatestShipDate().toString(), ShippedByAmazonTFM,
					ShipServiceLevel, ord.getMarketplaceId().get(0), LatestDeliveryDate, PurchaseDat, shipAddress,
					ord.getPaymentMethod().get(0), ord.getIsBusinessOrder().get(0), orderTotal,
					ord.getLastUpdateDate().toString(), ord.getShipmentServiceLevelCategory().get(0));
			System.out.println(ord.toString());

			ebst.add(amazonInfo);

			File file = excel.write("亚马逊订单信息", ebst, AmazonInfo.class,null);
			System.out.println("文件存放路径为：" + file.getPath());

			try {
				new ListOrdersByNextTokenSample().nextTokenOrder(nextToken);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			return response;

		} catch (MarketplaceWebServiceOrdersException ex) {
			// Exception properties are important for diagnostics.
			System.out.println("Service Exception:");
			ResponseHeaderMetadata rhmd = ex.getResponseHeaderMetadata();
			if (rhmd != null) {
				System.out.println("RequestId: " + rhmd.getRequestId());
				System.out.println("Timestamp: " + rhmd.getTimestamp());
			}
			System.out.println("Message: " + ex.getMessage());
			System.out.println("StatusCode: " + ex.getStatusCode());
			System.out.println("ErrorCode: " + ex.getErrorCode());
			System.out.println("ErrorType: " + ex.getErrorType());
			throw ex;
		}
	}

	/**
	 * Command line entry point.
	 */
	public static void main(String[] args) {

		// Get a client connection.
		// Make sure you've set the variables in
		// MarketplaceWebServiceOrdersSampleConfig.
		MarketplaceWebServiceOrdersClient client = MarketplaceWebServiceOrdersSampleConfig.getClient();

		// Create a request.
		ListOrdersByNextTokenRequest request = new ListOrdersByNextTokenRequest();
		String sellerId = "A31FK1YOBVUT0K";
		request.setSellerId(sellerId);
		String mwsAuthToken = "example";
		request.setMWSAuthToken(mwsAuthToken);
		String nextToken = "7lFviHgtX9h/YYuZQbKv1QafEPREmauvizt1MIhPYZZJmEd9UfhpcXMXrhAERS3NukcmlfaYSVvNeGyEmOrLe7q8xqAchQNKtU38YwqRuVIwqcbUqh/LhCJ0wMvlylZkE3RvwDUQBA1G6ShfNgiExhKFL/RxM5pTRcAcYEgjGoxWL0SZZXGXWx35jNz11rwFT4mKBv/7QdWLpq54KmAdgf0IfGeAvb95J/gMIjfO756fpVJGS+vu5pFHMXy6XL5lMbGym30ZxthC2G4bGXTY5bbONS6yTSc9sJdJobvDtjYGtweTBI2dtZUzYV7MlAUoEHeeaI4WsQaok31kqFVwo79xcusGG5a1fwylPI5qZH51NMrpM18PB5GesRwkZOQCBLVDshZ93sHthhfBGj6DwpxMeJyv/sQd25news0zC1xJrMt7LGOkAERAviLsW3erQcUy0ECq5T0G0BWizBLheyJl1k/lKJWCDSCc5FUR0o6wOLZvbeQauErDiHqb8mBE+aJntlBKfA830k98LaeuFDxxJb9jOEFB";
		request.setNextToken(nextToken);

		// Make the call.
		ListOrdersByNextTokenSample.invokeListOrdersByNextToken(client, request);

	}

	public void nextTokenOrder(String nextToken) throws Exception {

		MarketplaceWebServiceOrdersClient client = MarketplaceWebServiceOrdersSampleConfig.getClient();

		// Create a request.
		ListOrdersByNextTokenRequest request = new ListOrdersByNextTokenRequest();
		String sellerId = "A31FK1YOBVUT0K";
		request.setSellerId(sellerId);
		String mwsAuthToken = "example";
		request.setMWSAuthToken(mwsAuthToken);
		request.setNextToken(nextToken);

		// Make the call.
		ListOrdersByNextTokenSample.invokeListOrdersByNextToken(client, request);

	}

}
